/**
 * Copyright &copy; 2012-2013  All rights reserved.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.code.platform.common.utils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具类, 继承org.apache.commons.lang3.StringUtils类
 * @author unknown
 * @version 2013-05-22
 */
public class StringUtils extends org.apache.commons.lang3.StringUtils {

    /**
     * 替换掉HTML标签方法
     */
    public static String replaceHtml(String html) {
        if (isBlank(html)) {
            return "";
        }
        String regEx = "<.+?>";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(html);
        return m.replaceAll("");
    }

    /**
     * 缩略字符串（不区分中英文字符）
     * @param str 目标字符串
     * @param length 截取长度
     * @return 缩略字符串
     */
    public static String abbr(String str, int length) {
        if (str == null) {
            return "";
        }
        try {
            StringBuilder sb = new StringBuilder();
            int currentLength = 0;
            for (char c : str.toCharArray()) {
                currentLength += String.valueOf(c).getBytes("GBK").length;
                if (currentLength <= length - 3) {
                    sb.append(c);
                } else {
                    sb.append("...");
                    break;
                }
            }
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 转换为Double类型
     */
    public static Double toDouble(Object val) {
        if (val == null) {
            return 0D;
        }
        try {
            return Double.valueOf(trim(val.toString()));
        } catch (Exception e) {
            return 0D;
        }
    }

    /**
     * 转换为Float类型
     */
    public static Float toFloat(Object val) {
        return toDouble(val).floatValue();
    }

    /**
     * 转换为Long类型
     */
    public static Long toLong(Object val) {
        return toDouble(val).longValue();
    }

    /**
     * 转换为Integer类型
     */
    public static Integer toInteger(Object val) {
        return toLong(val).intValue();
    }

    /**
     * 转换为String类型
     */
    public static String toString(Object val) {
        if (val == null) {
            return null;
        }
        return String.valueOf(val);
    }

    /**
     * 获得父id字符串中的最后,
     */
    public static List<Long> getParentIds(Long id, String parentIds) {
        List<Long> list = new ArrayList<Long>();
        list.add(id);
        if (isNotBlank(parentIds)) {
            String[] arr = parentIds.split(",");
            for (String str : arr) {
                if (isNotBlank(str)) {
                    list.add(Long.valueOf(str));
                }
            }
        }
        return list;
    }

    /**
     * 将对象数组转换为可显字符串
     *
     * @param objArr 对象数组
     *
     * @return 可显字符串
     */
    public static String toString(Object[] objArr) {
        if (objArr == null) {
            return null;
        }

        StringBuffer buf = new StringBuffer("[");
        for (int i = 0; i < objArr.length; i++) {
            buf.append((i > 0 ? "," : "")).append(objArr[i]);
        }
        buf.append("]");
        return buf.toString();
    }

    /**
     * 把数字字母字符串格式化为MAC地址
     * @param str  数字字母字符串
     * @return MAC地址
     */
    public static String getFormatMac(String str) {
        if (isBlank(str)) {
            return null;
        }
        StringBuilder sb = new StringBuilder();

        str = str.toUpperCase().trim();
        int len = 0;
        for (int i = 0; i < str.length(); i++) {
            if (Character.isLetterOrDigit(str.charAt(i))) {
                sb.append(str.charAt(i));
                len++;
                // 达到MAC地址的位数要求
                if (len == 12) {
                    break;
                }
                if (len % 2 == 0) {
                    sb.append(":");
                }
            }
        }

        if (StringUtils.endsWith(sb, ":")) {
            sb.deleteCharAt(sb.length() - 1);
        }

        return sb.toString();
    }

    /**
     * 判断是不是MAC地址
     * @param mac 字符串
     * @return 是MAC地址：true；不是是MAC地址：false
     */
    public static boolean isMAC(String mac) {
        Pattern pattern = Pattern.compile("^([0-9a-fA-F]{2})(([/\\s:-][0-9a-fA-F]{2}){5})$");
        Matcher matcher = pattern.matcher(mac);
        return matcher.find();
    }

    /**
     * 验证邮箱是否正确
     * @param email 字符串
     * @return true:邮箱名正确；false:邮箱名不正确
     */
    public static boolean isEmail(String email) {
        String format = "\\p{Alpha}\\w{2,15}[@][a-z0-9]{3,}[.]\\p{Lower}{2,}";
        return email.matches(format);
    }

    public static boolean emailFormat(String email)
    {
        boolean tag = true;
        final String pattern1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        final Pattern pattern = Pattern.compile(pattern1);
        final Matcher mat = pattern.matcher(email);
        if (!mat.find()) {
            tag = false;
        }
        return tag;
    }

    /**
     * 判断是否在List中
     */
    public static boolean contains(String str, List list) {
        return list.contains(str);
    }

    /**
     * <p>Checks if the String contains only unicode digits or dot
     * (<code>' '</code>).
     * A decimal point is not a unicode digit and returns false.</p>
     *
     * <p><code>null</code> will return <code>false</code>.
     * An empty String ("") will return <code>true</code>.</p>
     *
     * <pre>
     * StringUtils.isNumericDot(null)   = false
     * StringUtils.isNumericDot("")     = false
     * StringUtils.isNumericDot(".")   = false
     * StringUtils.isNumericDot("123.")  = false
     * StringUtils.isNumericDot("123")  = true
     * StringUtils.isNumericDot("12.3") = true
     * StringUtils.isNumericDot("ab2c") = false
     * StringUtils.isNumericDot("12-3") = false
     * StringUtils.isNumericDot("12.3") = true
     * </pre>
     *
     * @param str  the String to check, may be null
     * @return <code>true</code> if only contains digits or space,
     *  and is non-null
     */
    public static boolean isNumericDot(String str) {
        if (str == null || str.isEmpty() || str.endsWith(".") || str.startsWith(".")) {
            return false;
        }
        int sz = str.length();
        for (int i = 0; i < sz; i++) {
            if ((Character.isDigit(str.charAt(i)) == false) && (str.charAt(i) != '.')) {
                return false;
            }
        }
        return true;
    }

    public static String getPhoneBy(String phone){
        if(isBlank(phone)){
            return phone;
        }
        if(phone.length()<11){
            return phone;
        }
        return phone.substring(0,3) + "****" + phone.substring(7, phone.length());
    }

   /* public static String getIdCardBy(String idCard){
        if(isBlank(idCard)){
            return idCard;
        }
        if(idCard.length()<4){
            return idCard;
        }
        return idCard.substring(0,idCard.length()-4) + "****" ;
    }*/



    /**
     * 隐藏身份证号中的部分以保护信息安全
     *
     * @param idCard 身份证号
     * @return 隐藏一部分信息的身份证号
     */
    public static String getIdCardBy(String idCard) {
        if (isBlank(idCard)) {
            return idCard;
        }
        if (idCard.length() < 4) {
            return idCard;
        }

        if (idCard.length() < 15) {
            return idCard;
        }

        if (idCard.length() == 15) {
            //老的15位身份证号
            return idCard.substring(0, 5) + "******" + idCard.substring(12, 15);
        }

        if (idCard.length() == 18) {
            //新的18位身份证号
            return idCard.substring(0, 5) + "**********" + idCard.substring(15, 18);
        }

        return idCard.substring(0, 5) + "**********" + idCard.substring(15, idCard.length());
    }
}
